<?php

/**
 * @version			$Id$
 * @create 			2012-04-21 11:04:10 By xjiujiu
 * @description     HongJuZi Framework
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
defined('_HEXEC') or die('Restricted access!');

//导入模块工具类
HClass::import('config.popo.orderpopo, app.admin.action.AdminAction, model.ordermodel');

/**
 * 用户角色的动作类 
 * 
 * 主要处理后台管理主页的相关请求动作 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.admin.action
 * @since 			1.0.0
 */
class ReportcountAction extends AdminAction
{

    /**
     * 构造函数 
     * 
     * 初始化类变量 
     * 
     * @access public
     */
    public function __construct() 
    {
        parent::__construct();
        $this->_popo        = new OrderPopo();
        $this->_model       = new OrderModel($this->_popo);
        $this->_setStartEndTimeValue();
    }

    /**
     * 首页
     */
    public function index()
    {
        HResponse::redirect(HResponse::url('reportcount/ordercount', '', 'admin'));
    }

    /**
     * 上菜时效统计
     */
    public function caitime()
    {
        $this->_popo->modelEnName = 'reportcount';
        $this->_popo->modelZhName = '订单统计';
        $startDate      = HRequest::getParameter('start_time');
        $startDate      = !$startDate ? date('Y-m-d') . ' 00:00:00' : $startDate;
        $startTime      = strtotime($startDate);
        $endDate        = HRequest::getParameter('end_time');
        $endDate        = !$endDate ? date('Y-m-d H:i:s', $startTime + 86400) : $endDate . ' 23:59:59';
        $endTime        = strtotime($endDate);
        $where          = '`create_time` >= \'' . $startDate . '\' AND `create_time` <= \'' . $endDate . '\'';
        if($endTime - $startTime > 5356800) {
            throw new HVerifyException('统计时间长度不能超过62天！');
        }
        $finishWhere    = $where . ' AND `cai_done_time` > 0';//订单完成
        $totalRows      = $this->_model->getTotalRecords($finishWhere);
        $list           = $this->_model->getAllRowsByFields(
            '`id`, `name`, `create_time`, `cai_use_time`',
            $finishWhere
        );
        $data           = array();
        $xAxis          = array();
        foreach($list as $item) {
            $time       = strtotime($item['create_time']);
            $min        = $item['cai_use_time'] / 60;
            $data[]     = number_format($min, 2);
            $xAxis[]    = date('m-d H:i', $time);
        }
        $this->_commAssign();
        HResponse::setAttribute('data', json_encode($data));
        HResponse::setAttribute('xAxis', json_encode($xAxis));
        HResponse::setAttribute('endDate', $endDate);
        HResponse::setAttribute('startDate', $startDate);
        HResponse::setAttribute('totalRows', $totalRows);
        $this->_render('reportcount/caitime-count');
    }

    /**
     * 订单统计
     */
    public function ordercount()
    {
        $startTime  = strtotime(HRequest::getParameter('start_time') . ' 00:00:00');
        $endTime    = strtotime(HRequest::getParameter('end_time') . ' 23:59:59');
        $this->_popo->modelEnName = 'reportcount';
        $this->_popo->modelZhName = '订单统计';
        $preWhere       = $this->_combineWhere();
        $order          = HClass::quickLoadModel('Order');
        $xAxis                  = array();
        $waitPayCountList       = array();
        $finishCountList        = array();
        $tuikuanCountList       = array();
        $cancelCountList        = array();
        $totalMoneyList         = array();
        $totalNumberList        = array();
        while($startTime < $endTime) {
            $xAxis[]        = date('y-m-d', $startTime);
            $where          = $preWhere . ' AND `create_time` >= \'' . date('Y-m-d H:i:s', $startTime) . '\''. ' AND `create_time` <= \'' . date('Y-m-d H:i:s', $startTime + 86400) . '\'';

            $finishWhere    = $where . ' AND `status` in (3, 10, 4)';//订单完成
            $tuikuanWhere   = $where . ' AND `status` in (7, 8)';//退款
            $cancelWhere    = $where . ' AND `status` = 5';//订单取消
            $totalMoneyList[]   = $this->_model->getSum('amount', $where . ' AND `status` = 4');
            $totalNumberList[]  = $this->_model->getSum('number', $where . ' AND `status` = 4');
            $finishCountList[]  = $this->_model->getTotalRecords($finishWhere);
            $tuikuanCountList[] = $this->_model->getTotalRecords($tuikuanWhere);
            $cancelCountList[]  = $this->_model->getTotalRecords($cancelWhere);
            $startTime          += 86400;
        }

        HResponse::setAttribute('xAxis', $xAxis);
        HResponse::setAttribute('totalMoneyList', $totalMoneyList);
        HResponse::setAttribute('totalNumberList', $totalNumberList);
        HResponse::setAttribute('finishCountList', $finishCountList);
        HResponse::setAttribute('tuikuanCountList', $tuikuanCountList);
        HResponse::setAttribute('cancelCountList', $cancelCountList);
        $this->_commAssign();

        $this->_render('reportcount/order-count');
    }

    /**
     * 销售排行
     */
    public function goodssale()
    {
        $startTime      = HRequest::getParameter('start_time') . ' 00:00:00';
        $endTime        = HRequest::getParameter('end_time') . ' 23:59:59';
        $this->_popo->modelEnName = 'reportcount';
        $this->_popo->modelZhName = '销售排行';
        $goods          = HClass::quickLoadModel('Goods');
        $orderGoods     = HClass::quickLoadModel('Ordergoods');
        $where          = $this->_combineWhere();
        $where          .= ' AND `status` = 2';
        if($startTime && $endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\' AND `create_time` <= \'' . $endTime . '\'';
        }else if($startTime && !$endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\'';
        }else if(!$startTime && $endTime){
            $where      .= ' AND `create_time` <= \'' . $endTime . '\'';
        }
        $goodsWhere     = '1 = 2';
        if(HResponse::getAttribute('shop_id')) {
            $goodsWhere = '`shop_id` = ' . HResponse::getAttribute('shop_id');
            $shopGoodsList = $goods->getAllRowsByFields('`id`, `name`', $goodsWhere);
            if($shopGoodsList) {
                $where .= ' AND ' . HSqlHelper::whereInByListMap('goods_id', 'id', $shopGoodsList);
            }
            $shopInfo = HResponse::getAttribute('shopInfo');
            $this->_popo->modelZhName   = $shopInfo['name'] . '供货商销售排行';
        }
        $goodsList      = $goods->getAllRowsByFields('`id`, `name`', $goodsWhere);
        $orderGoodsList = $orderGoods->getAllRows($where);
        $data           = array();
        foreach($orderGoodsList as $item){
            if(isset($data[$item['goods_id']])){
                $data[$item['goods_id']]['price']       = $item['price'];
                $data[$item['goods_id']]['number']      += $item['number'];
                $data[$item['goods_id']]['total_price'] += $item['price'] * $item['number'];
                $data[$item['goods_id']]['avg_price']   = number_format($data[$item['goods_id']]['total_price'] / $data[$item['goods_id']]['number'], 2);
            }else{
                $data[$item['goods_id']]['price']       = $item['price'];
                $data[$item['goods_id']]['number']      = $item['number'];
                $data[$item['goods_id']]['total_price'] = $item['price'] * $item['number'];
                $data[$item['goods_id']]['avg_price']   = $item['price'];
            }
        }
        $list           = array();
        $temp           = array();
        foreach($goodsList as $k => $v){
            $list[$k]['id']         = $v['id'];
            $list[$k]['name']       = $v['name'];
            $list[$k]['number']     = intval($data[$v['id']]['number']);
            $list[$k]['total_price']= floatval($data[$v['id']]['total_price']);
            $list[$k]['avg_price']  = floatval($data[$v['id']]['avg_price']);
            $temp[]                 = $list[$k]['number'];
        }
        array_multisort($temp, $list);
        $list = array_reverse($list);
        HResponse::setAttribute('list', $list);
        HResponse::setAttribute('goodsList', $goodsList);
        $this->_assignGoodsCatList();
        $this->_commAssign();

        $this->_render('reportcount/goods-sale');
    }

    private function _assignGoodsCatList()
    {
        $goodsCat   = HClass::quickLoadModel('goodscategory');
        $list       = $goodsCat->getAllRowsByFields('`id`, `name`, `parent_id`', '1 = 1');
        HResponse::setAttribute('catList', $list);
    }

    /**
     * 会员排行
     */
    public function usersort()
    {
        $startTime      = HRequest::getParameter('start_time') . ' 00:00:00';
        $endTime        = HRequest::getParameter('end_time') . ' 23:59:59';
        $this->_popo->modelEnName = 'reportcount';
        $this->_popo->modelZhName = '会员排行';
        $where          = $this->_combineWhere();
        $user           = HClass::quickLoadModel('User');
        $actor          = HClass::quickLoadModel('Actor');
        $actorRecord    = $actor->getRecordByIdentifier('member');
        $where          .= ' AND `status` in (3,4)';
        if($startTime && $endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\' AND `create_time` <= \'' . $endTime . '\'';
        }else if($startTime && !$endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\'';
        }else if(!$startTime && $endTime){
            $where      .= ' AND `create_time` <= \'' . $endTime . '\'';
        }
        $perpage        = 10;
        $totalRows      = $this->_model->getTotalByGroup('count(1)', $where);
        $totalPages     = ceil($totalRows / $perpage);
        $page           = $this->_getPageNumber($totalPages);
        $orderList      = $this->_model->getUserSortList($where, $page, $perpage);
        $userList       = $user->getAllRows(
            '`parent_id` = ' . $actorRecord['id'] 
            . ' AND ' . HSqlHelper::whereInByListMap('id', 'parent_id', $orderList)
        );
        $userListMap    = HArray::turnItemValueAsKey($userList, 'id');
        $list           = array();
        foreach($orderList as $key => $item){
            $list[$key]['total_order'] = $key + 1;
            $list[$key]['name'] = $userListMap[$item['parent_id']]['name'];
            $list[$key]['total_order'] = $item['total'];
            $list[$key]['total_money'] = $item['amount'];
        }
        $pageHtml   = $this->_genPageHtml($page + 1, $totalPages, 'page');
        HResponse::setAttribute('list', $list);
        HResponse::setAttribute('totalRows', $totalRows);
        HResponse::setAttribute('curPage', $page + 1);
        HResponse::setAttribute('totalPages', $totalPages);
        HResponse::setAttribute('pageHtml', $pageHtml);
        $this->_commAssign();

        $this->_render('reportcount/user-sort');
    }

    /**
     * 供货商排名
     * @return [type] [description]
     */
    public function shopsale()
    {
        $startTime      = HRequest::getParameter('start_time') . ' 00:00:00';
        $endTime        = HRequest::getParameter('end_time') . ' 23:59:59';
        $this->_popo->modelEnName = 'reportcount';
        $this->_popo->modelZhName = '供货商排行';
        $goods          = HClass::quickLoadModel('goods');
        $shop           = HClass::quickLoadModel('shop');
        $goodsList      = $goods->getAllRowsByFields('`id`, `name`, `shop_id`', '`shop_id` > 0');
        $shopMap        = HArray::turnItemValueAsKey(
            $shop->getAllRowsByFields(
            '`id`, `name`', HSqlHelper::whereInByListMap('id', 'shop_id', $goodsList)
        ), 'id');
        $goodsMap       = HArray::turnItemValueAsKey($goodsList, 'id');
        $where          = '`status` = 2 AND ' . HSqlHelper::whereInByListMap('goods_id', 'id', $goodsList);
        if($startTime && $endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\' AND `create_time` <= \'' . $endTime . '\'';
        }else if($startTime && !$endTime){
            $where      .= ' AND `create_time` >= \'' . $startTime . '\'';
        }else if(!$startTime && $endTime){
            $where      .= ' AND `create_time` <= \'' . $endTime . '\'';
        }
        $orderGoods     = HClass::quickLoadModel('orderGoods');
        $list   = $orderGoods->getAllRowsByFields('`id`, `number`, `goods_id`', $where);
        $data   = array();
        foreach($shopMap as $key => $shop) {
            $data[$shop['id']]['id']    = $shop['id'];
            $data[$shop['id']]['name']  = $shop['name'];
            $data[$shop['id']]['total'] = 0;
        }
        foreach($list as $key => $item) {
            $shopId     = $goodsMap[$item['goods_id']]['shop_id'];
            $data[$shopId]['total'] += $item['number'];
        }
        $data   = HArray::arraySort($data, 'total', 'desc');        
        HResponse::setAttribute('list', $data);
        $this->_assignQuickTime();        
        $this->_commAssign();

        $this->_render('reportcount/shop-sale');
    }

    /**
     * 加载快捷时间
     * @return [type] [description]
     */
    private function _assignQuickTime()
    {
        $now        = date('Y-m-d', time());
        $yestMonth  = date('Y-m-d', strtotime('-1 month'));
        $yestDay    = date('Y-m-d', strtotime('-7 day'));
        $yestYear   = date('Y-m-d', strtotime('-1 year'));
        HResponse::setAttribute(
            'sevDayUrl', 
            HResponse::url('reportcount/shopsale', 'start_time=' . $yestDay . '&end_time=' . $now)
        );
        HResponse::setAttribute(
            'oneMonthUrl',
            HResponse::url('reportcount/shopsale', 'start_time=' . $yestMonth . '&end_time=' . $now)  
        );
        HResponse::setAttribute(
            'oneYearUrl',
            HResponse::url('reportcount/shopsale', 'start_time=' . $yestYear . '&end_time=' . $now)  
        );
    }

}

?>
